package gov.kqqzyyy.monkey.orderpad.ui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.IdRes;

import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.orderpad.R;
import gov.kqqzyyy.monkey.orderpad.adapter.OrderDetailAdapter;
import gov.kqqzyyy.monkey.orderpad.mytools.DateTimeUtil;
import gov.kqqzyyy.monkey.orderpad.network.RetrofitUtil;
import gov.kqqzyyy.monkey.orderpad.network.base.BaseObserver;
import gov.kqqzyyy.monkey.orderpad.network.bean.BaseResponse;
import gov.kqqzyyy.monkey.orderpad.object.DD_DDMX;
import gov.kqqzyyy.monkey.orderpad.object.FloorPatient;
import gov.kqqzyyy.monkey.orderpad.object.post_param.CancelOrder_Param;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

@SuppressLint("NonConstantResourceId")
public class OrderCheckActivity2 extends NavigationBaseActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, AdapterView.OnItemSelectedListener, AdapterView.OnItemLongClickListener {


    @BindView(R.id.container)
    FrameLayout container;

    Button mReOrderBtn;
    ListView mOrderListView;
    RadioGroup mRadioGroup;
    TextView mPatientBed, mPatientName, mPatientSex, mPatientPhone;
    Spinner mFloorSpinner, mBedSpinner;

    private OrderDetailAdapter mOrderAdapter;
    private List<DD_DDMX> mOrderList;
    private List<DD_DDMX> mShowOrderList;

    private FloorPatient choosePatient;

    private DD_DDMX mOrderDetail;

//    private int whichTask;
//    private WxTKReturn wxTKReturn;
//    private Call<String> dcddCall;

    private BaseObserver<String> cancelObserver;
    private BaseObserver<List<DD_DDMX>> dcddObserver;

    private final Handler myHandler = new Handler();
    private final Runnable mLoadingRunnable = this::loadView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    private void loadView() {

        container.removeAllViews();
        LayoutInflater.from(this).inflate(R.layout.activity_order_check_v2, container);
        onBindUI();

        mReOrderBtn.setOnClickListener(this);
        mOrderAdapter = new OrderDetailAdapter(this);
        mOrderListView.setAdapter(mOrderAdapter);
        mOrderListView.setOnItemLongClickListener(this);

        mRadioGroup.setOnCheckedChangeListener(this);
        mFloorSpinner.setOnItemSelectedListener(this);
        mBedSpinner.setOnItemSelectedListener(this);

        setFloor();
    }

    private void onBindUI() {
        mReOrderBtn = findViewById(R.id.order_check_reorder_btn);
        mOrderListView = findViewById(R.id.order_check_orderlist);
        mRadioGroup = findViewById(R.id.order_check_radiogroup);
        mPatientBed = findViewById(R.id.order_check_patient_bednum);
        mPatientName = findViewById(R.id.order_check_patient_name);
        mPatientSex = findViewById(R.id.order_check_patient_sex);
        mPatientPhone = findViewById(R.id.order_check_patient_phone);
        mFloorSpinner = findViewById(R.id.order_check_floor_choose_spinner);
        mBedSpinner = findViewById(R.id.order_check_bed_choose_spinner);
        setmFloorSpinner(mFloorSpinner);
        setmBedSpinner(mBedSpinner);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getWindow().getDecorView().post(() -> myHandler.post(mLoadingRunnable));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                int position = mOrderListView.getSelectedItemPosition();
                if (mShowOrderList != null && mShowOrderList.size() > position && position >= 0) {
                    mOrderDetail = mShowOrderList.get(position);
                    showMenuDialog();
                }
                break;
            case KeyEvent.KEYCODE_BACK:
                backToOrderMenu();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showMenuDialog() {
//        final String[] items = new String[]{"订单付款", "取消订单"};
        final String[] items = new String[]{"取消订单"};
        AlertDialog.Builder mChooseDialogBuilder = new AlertDialog.Builder(OrderCheckActivity2.this);
        mChooseDialogBuilder.setTitle("订单操作");
        mChooseDialogBuilder.setItems(items, (dialogInterface, which) -> {
//            doCancelOrder(mOrderDetail.getDdh(), "0.00", mOrderDetail.getFyxh(), mOrderDetail.getZffs());
            doCancelOrder(mOrderDetail.getDdh());
//            whichTask = which;
//            switch (which) {
//                case 0: //付款操作
//                    Toast.makeText(getApplicationContext(), "功能暂未开启", Toast.LENGTH_SHORT).show();
////                    switch (mOrderDetail.getDDZT()) {
////                        case "0"://若订单未付款则弹出付款二维码
////                            doCancelOrPayTask();
////                            break;
////                        case "1":
////                            Toast.makeText(OrderCheckActivity2.this, "订单已付款！", Toast.LENGTH_SHORT).show();//提示订单状态
////                            break;
////                        case "2":
////                            Toast.makeText(OrderCheckActivity2.this, "订单已取消！", Toast.LENGTH_SHORT).show();//提示订单状态
////                            break;
////                    }
//                    break;
//                case 1://取消订单操作
//                    if (!mOrderDetail.getDDZT().equals("2")) {//满足取消条件
////                        doVerify();//用户身份验证
//                        whichTask = 1;
////                        doVerify();
//                        doCancelOrPayTask();
//                    } else {
//                        Toast.makeText(getApplicationContext(), "该订单不满足取消条件!", Toast.LENGTH_SHORT).show();
//                    }
//                    break;
//            }
        });
        mChooseDialogBuilder.show();
    }

//    //用户身份验证（登陆窗口）
//    private void doVerify() {
//        LoginConfirmDialog loginConfirmDialog = new LoginConfirmDialog();
//        loginConfirmDialog.setLoginAccount(getMySharedPreferences().getString("account", ""));
//        loginConfirmDialog.setLoginPW("123");
//        loginConfirmDialog.show(getFragmentManager(), "LoginConfirm");
//    }


//    //执行付款、退款、取消订单操作
//    public void doCancelOrPayTask() {
//        switch (whichTask) {
////            case 0: //付款操作，弹出二维码窗口
////                WXPayDialogFragment wxPayDialogFragment = new WXPayDialogFragment();
////                wxPayDialogFragment.setSUCCESS_DDH(mOrderDetail.getDDH());
////                wxPayDialogFragment.setSUCCESS_PRICE(mOrderDetail.getZJG());
////                wxPayDialogFragment.setPATIENT_ZYH(mOrderDetail.getBRZYH());
////                wxPayDialogFragment.show(getFragmentManager(), "PayDialog");
////                break;
//            case 1://取消订单操作
////                if (mOrderDetail.getFKBZ().equals("1")) {//已经付款，需要先退款
////                    new AlertDialog.Builder(OrderCheckActivity2.this)
////                            .setTitle("订单取消提醒")
////                            .setMessage("该订单已经付款，取消订单将自动退款，是否继续？")
////                            .setPositiveButton("确定", (dialogInterface, i) -> {
////                                String refundNo = "TK" + mOrderDetail.getDDH();
////                                doRefund(mOrderDetail.getSHDDH(), refundNo, choosePatient.getBrbh(), mOrderDetail.getZJG(), mOrderDetail.getZJG());
////                            }).setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss())
////                            .show();
////                } else {//未付款，直接取消
//
//                doCancelOrder(mOrderDetail.getDDH(), "0.00", mOrderDetail.getFYXH(), mOrderDetail.getZFFS());
//
////                }
//                break;
//        }
//    }

    private void backToOrderMenu() {
        Intent intent = new Intent(getApplicationContext(), OrderMenuActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
        finish();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.order_check_reorder_btn) {
            backToOrderMenu();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if (dcddCall != null && dcddCall.isExecuted()) {
//            dcddCall.cancel();
//        }
        if (cancelObserver != null) {
            cancelObserver.doCancelRequest();
        }
        if (dcddObserver != null) {
            dcddObserver.doCancelRequest();
        }
    }

    public void doFlushOrderList() {
        doGetPatientDCDD(choosePatient.getBrbh());
    }

    //设置病人信息
    private void setPatientInfo(FloorPatient patient) {
        String bed = "床号：";
        String name = "姓名：";
        String sex = "性别：";
        String phone = "电话：";
        if (patient != null) {
            bed += getChooseCH();
            name += patient.getBrxm();
            sex += patient.getBrxb();
            phone += patient.getLxdh();
        }
        mPatientBed.setText(bed);
        mPatientName.setText(name);
        mPatientSex.setText(sex);
        mPatientPhone.setText(phone);
    }

    //订单过滤
    private void doFilterOrder() {
        int whichID = mRadioGroup.getCheckedRadioButtonId();
        Date dateNow = new Date(System.currentTimeMillis());
        dateNow.setTime(dateNow.getTime() + getMyApplication().getDeltaTime());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateNow);
        String startTime = null;
        switch (whichID) {
            case R.id.order_check_radiobtn_1:
                startTime = DateTimeUtil.getDFFormatString(calendar.getTime());
                break;
            case R.id.order_check_radiobtn_2:
                calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE) - 7);
                startTime = DateTimeUtil.getDFFormatString(calendar.getTime());
                break;
            case R.id.order_check_radiobtn_3:
                break;
        }
        mShowOrderList = new ArrayList<>();
        if (mOrderList != null) {
            if (startTime != null) {
                for (DD_DDMX ddmx : mOrderList
                ) {
                    if (ddmx.getXdsj().compareTo(startTime) > 0) {
                        mShowOrderList.add(ddmx);
                    }
                }
            } else {
                mShowOrderList.addAll(mOrderList);
            }
        }
        mOrderAdapter.setList(mShowOrderList);
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        doFilterOrder();
    }

    private void doGetPatientDCDD(String zyh) {
        KLog.d("APE", "获取订单信息");
        showProgressDialog("获取订单信息中");
        Observable<BaseResponse<List<DD_DDMX>>> observable = RetrofitUtil.getInstence().getPatientDCDDByZyh(zyh);
        dcddObserver = new BaseObserver<List<DD_DDMX>>() {
            @Override
            protected void onSuccees(BaseResponse<List<DD_DDMX>> t) {
                cancelProgressDialog();
                mOrderList = t.getData();
                if (mOrderList != null) {
                    doFilterOrder();
                }
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                cancelProgressDialog();
                showToast("获取订单失败\n" + e.getMessage());
                mOrderList = new ArrayList<>();
                mOrderAdapter.setList(mOrderList);
            }

            @Override
            protected void onCodeError(BaseResponse<List<DD_DDMX>> t) {
                super.onCodeError(t);
                cancelProgressDialog();
                showToast("获取订单失败\n" + t.getSubmsg());
                mOrderList = new ArrayList<>();
                mOrderAdapter.setList(mOrderList);
            }

        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(dcddObserver);


//        dcddCall = MyServiceUtil.getPatientDCDDCall(zyh);
//        Callback<String> callback = new Callback<String>() {
//            @Override
//            public void onResponse(Call<String> call, Response<String> response) {
//                cancelProgressDialog();
//                String result = response.body();
//                if (result != null) {
//                    Gson gson = new Gson();
//                    mOrderList = gson.fromJson(result, new TypeToken<List<OrderDetail>>() {
//                    }.getType());
//                    if (mGetOrderList != null) {
//                        doFilterOrder();
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(Call<String> call, Throwable t) {
//                cancelProgressDialog();
//                Toast.makeText(getApplicationContext(), "获取病人信息失败：" + t.toString(), Toast.LENGTH_SHORT).show();
//            }
//        };
//        dcddCall.enqueue(callback);
    }

    private void doCancelOrder(String dcddh) {
        showProgressDialog("取消订单中");
        CancelOrder_Param param = new CancelOrder_Param(choosePatient.getBrbh(), dcddh);
        Observable<BaseResponse<String>> observable = RetrofitUtil.getInstence().doCancelOrder(param);
        cancelObserver = new BaseObserver<String>() {
            @Override
            protected void onSuccees(BaseResponse<String> t) {
                cancelProgressDialog();
                showToast(t.getData());
                doFlushOrderList();
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                cancelProgressDialog();
                KLog.d("APE", e.getMessage());
                showToast("取消订单失败\n" + e.getMessage());
            }

            @Override
            protected void onCodeError(BaseResponse<String> t) {
                super.onCodeError(t);
                cancelProgressDialog();
                KLog.d("APE", t.getMsg());
                showToast("取消订单失败\n" + t.getSubmsg());

            }

        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(cancelObserver);


//        String qqsj = DateTimeUtil.getDateTimeFormat(new Date());
//        Call<String> qxddCall = MyServiceUtil.cancelOrderCall(dcddh, qqsj, tkje, tkdh, zffs);
//        Callback<String> callback = new Callback<String>() {
//            @Override
//            public void onResponse(Call<String> call, Response<String> response) {
//                cancelProgressDialog();
//                String result = response.body();
//                if (result != null) {
//                    Gson gson = new Gson();
//                    MessageReturn messageReturn = gson.fromJson(result, new TypeToken<MessageReturn>() {
//                    }.getType());
//                    String showMessage;
//                    if (messageReturn.getMsg().startsWith("FAIL")) {
//                        showMessage = "退款失败，请联系信息科！";
//                    } else {
//                        showMessage = "取消订单成功！";
//                    }
//                    Toast.makeText(getApplicationContext(), showMessage, Toast.LENGTH_SHORT).show();
//                    //                    result = result.replace("\"", "");
////                    String[] xmlPart = result.split(",");
////                    if (!xmlPart[0].equals("FAIL")) {
////                        Toast.makeText(getApplicationContext(), "修改退款状态成功！", Toast.LENGTH_SHORT).show();
////                    }
//                }
//                doFlushOrderList();
//            }
//
//            @Override
//            public void onFailure(Call<String> call, Throwable t) {
//                cancelProgressDialog();
//                Toast.makeText(getApplicationContext(), "提交退款失败：" + t.toString(), Toast.LENGTH_SHORT).show();
//            }
//        qxddCall.enqueue(callback);
    }

//    private void doRefund(String out_trade_no, String out_refund_no, String op_user_id, String total_fee, String refund_fee) {
//        showProgressDialog("退款申请中");
//        Call<String> refunCall = MyServiceUtil.getRefundCall(out_trade_no, out_refund_no, op_user_id, total_fee, refund_fee);
//        Callback<String> callback = new Callback<String>() {
//            @Override
//            public void onResponse(Call<String> call, Response<String> response) {
//                cancelProgressDialog();
//                String result = response.body();
//                result = result.replace("\"", "");
//                String[] xmlResult = result.split(",");
//                if (!xmlResult[0].equals("FAIL")) {
//                    Toast.makeText(getApplicationContext(), "退款已提交！", Toast.LENGTH_SHORT).show();
//                    wxTKReturn = XMLUtils.readXML(xmlResult[1], WxTKReturn.class);
//                    doCancelOrder(mOrderDetail.getDDH(), mOrderDetail.getZJG(), wxTKReturn.getOut_refund_no());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<String> call, Throwable t) {
//
//                cancelProgressDialog();
//                Toast.makeText(getApplicationContext(), "退款失败：" + t.toString(), Toast.LENGTH_SHORT).show();
//            }
//        };
//        refunCall.enqueue(callback);
//    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.order_check_bed_choose_spinner:
                choosePatient = doGetSelectPatientInfo(position);
                if (choosePatient != null) {
                    setPatientInfo(choosePatient);
                    doFlushOrderList();
                }
                break;
            case R.id.order_check_floor_choose_spinner:
                String chooseFloor = getMyApplication().getmFloorsNameList().get(position);
                getMyApplication().setChooseFloor(chooseFloor);
                changeFloor();
                break;
        }
    }

    @Override
    public void clearChoosePatientInfo() {
        super.clearChoosePatientInfo();
        choosePatient = null;
        setPatientInfo(null);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        mOrderDetail = mShowOrderList.get(position);
        if (!mOrderDetail.getDdzt().equals("2")) {
            showMenuDialog();
        }
        return false;
    }
}
